<template>
  <div class="user-page">
    <el-card>
      <template #header>
        <span style="font-size: 16px; color: #131523; font-weight: 500;">基本资料</span>
      </template>
      <el-form label-width="80px" :model="form" :rules="rules" ref="form">
        <el-form-item label="登录名称">
          <el-input style="width: 400px;" disabled v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickname">
          <el-input style="width: 400px;" v-model="form.nickname" placeholder="请输入用户昵称"></el-input>
        </el-form-item>
        <el-form-item label="用户邮箱" prop="email">
          <el-input style="width: 400px;" v-model="form.email" placeholder="请输入用户邮箱"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button style="background-color: #4F81FF; color: rgba(255,255,255,0.9);" @click="submit">提交修改</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getUserInfo, updateUserInfo } from '@/api/user'
export default {
  name: 'BasicInformation',
  data () {
    return {
      form: {
        username: '',
        nickname: '',
        email: '',
        user_pic: ''
      },
      rules: {
        nickname: [
          { required: true, message: '请输入用户昵称', trigger: ['blur', 'change'] },
          { min: 1, max: 10, message: '用户昵称需要1~10个字符', trigger: ['blur', 'change'] }
        ],
        email: [
          { required: true, message: '请输入用户邮箱', trigger: ['blur', 'change'] },
          { pattern: /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, message: '请输入正确格式的邮箱', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  created () {
    this.initData()
  },
  methods: {
    // 初始化页面
    async initData () {
      const res = await getUserInfo()
      console.log(res)
      this.form = res.data
    },
    // 提交修改后的用户基本信息
    async submit () {
      // 校验输入是否合规
      await this.$refs.form.validate()
      const res = await updateUserInfo(this.form)
      if (res.message !== '修改用户信息成功！') {
        this.$message.error(res.message)
        return
      }

      // 提示用户修改信息成功
      this.$message.success(res.message)
      // 重新渲染页面
      this.initData()

      this.$store.commit('user/setUserAvatar', this.form.user_pic)

      // 将修改后的用户昵称保存并渲染
      if (this.form.nickname) {
        this.$store.commit('user/getUserName', this.form.nickname)
      } else {
        this.$store.commit('user/getUserName', this.form.username)
      }
    },
    // 重置功能
    reset () {
      // 重置输入框内容
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style>

</style>
